package demo2;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Parameter;

public class Demo2 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {

        //学习通过class对象获取类内的构造方法

        Class clazz = Class.forName("demo2.Student");

        //获取构造方法学习
        //公有
        Constructor[] cons1 = clazz.getConstructors();
        for (Constructor con : cons1) {
            System.out.println(con);//获得所有的构造方法
        }

        Constructor[] cons2 = clazz.getDeclaredConstructors();
        for (Constructor con : cons2) {
            System.out.println(con);
        }
        System.out.println("==============");

       //获取单个构造方法
        Constructor con1 = clazz.getConstructor();
        System.out.println(con1);

        Constructor con2 = clazz.getConstructor(String.class);
        System.out.println(con2);

        Constructor con3 = clazz.getDeclaredConstructor(String.class, int.class);
        System.out.println(con3);

        //获得该构造方法的权限修饰符
        int modifiers = con3.getModifiers();
        System.out.println(modifiers);//1对应的就是private
        System.out.println("=================");
        //获得当前构造方法的形参
        Parameter[] parameters = con3.getParameters();
        for (Parameter p : parameters) {
            System.out.println(p);
        }
        System.out.println("----------------");

        //想要通过构造方法来创建对象
        //对私有的构造方法先进行暴力反射
        con3.setAccessible(true);
        //构造对象
        Student stu = (Student) con3.newInstance("zhangsan", 23);
        System.out.println(stu);
    }
}
